﻿using HPIT.RentHouse.Common;
using HPIT.RentHouse.DTO;
using HPIT.RentHouse.IService;
using HPIT.RentHouse.Service.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace HPIT.RentHouse.Service
{
    public class AdminUsersService : IAdminUsersService
    {
        /// <summary>
        /// 根据Id获取管理员信息
        /// </summary>
        /// <param name="id">权限Id</param>
        /// <returns></returns>
        public AdminUserDTO Get(long id)
        {
            RentHouseEntities db = new RentHouseEntities();
            BaseService<T_AdminUsers> baseService = new BaseService<T_AdminUsers>(db);
            var model = baseService.Get(a => a.Id == id);
            AdminUserDTO permissionDTO = new AdminUserDTO()
            {
                Id = model.Id,
                Email = model.Email,
                Name = model.Name,
                PhoneNum = model.PhoneNum,
                CityName = model.T_Cities.Name
            };
            return permissionDTO;
        }
        /// <summary>
        /// 查询角色信息
        /// </summary>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="name"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public List<AdminUserDTO> GetPagedList(int start, int length, string name, ref int rowCount)
        {
            RentHouseEntities db = new RentHouseEntities();
            BaseService<T_AdminUsers> baseService = new BaseService<T_AdminUsers>(db);
            var query = PredicateExtensions.True<T_AdminUsers>();
            if (!string.IsNullOrWhiteSpace(name))
            {
                query = query.And(a => a.Name.Contains(name));
            }
            var list = baseService.GetPagedList(start, length, ref rowCount, query, e => e.Id).Select(e => new AdminUserDTO
            {
                Id = e.Id,
                Name = e.Name,
                Email = e.Email,
                PhoneNum = e.PhoneNum,
                CityName = e.T_Cities.Name
            }).ToList();
            return list;
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="dto">角色信息</param>
        /// <returns></returns>
        public AjaxResult Add(AdminUserAddDTO dto)
        {
            //1、管理员表添加  2、关联表角色的添加
            using (var db = new RentHouseEntities())
            {
                var bs = new BaseService<T_AdminUsers>(db);
                var bsRole = new BaseService<T_Roles>(db);
                //验证手机号唯一
                var model = bs.Get(a => a.PhoneNum == dto.PhoneNum);
                if (model != null)
                {
                    return new AjaxResult(ResultState.Error, "添加管理员失败,该手机号已注册！");
                }

                model = new T_AdminUsers();
                model.Name = dto.Name;
                model.CreateDateTime = DateTime.Now;
                model.PhoneNum = dto.PhoneNum;
                model.LoginErrorTimes = 0;
                model.Email = dto.Email;
                model.CityId = dto.CityId;
                //采用MD5加盐加密的方式
                //1、获取盐(随机数）
                model.PasswordSalt = CommonHelper.CreateVerifyCode(5);
                //MD5加盐加密
                model.PasswordHash = CommonHelper.CalcMD5(dto.Password + model.PasswordSalt);
                if (dto.RoleIds != null && dto.RoleIds.Count > 0)
                {
                    foreach (var id in dto.RoleIds)
                    {
                        T_Roles role = bsRole.Get(e => e.Id == id);
                        model.T_Roles.Add(role);
                    }
                }

                if (bs.Add(model) > 0)
                {
                    return new AjaxResult(ResultState.Success, "添加管理员成功");
                }
                else
                {
                    return new AjaxResult(ResultState.Error, "添加管理员失败");
                }
            }
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        public AjaxResult Delete(long id)
        {
            var db = new RentHouseEntities();
            BaseService<T_AdminUsers> bs = new BaseService<T_AdminUsers>(db);
            var model = bs.Get(e => e.Id == id);
            if (bs.Delete(model))
            {
                return new AjaxResult(ResultState.Success, "删除角色成功");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "删除角色失败");
            }
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginDTO"></param>
        /// <returns></returns>
        public AjaxResult Login(LoginDTO loginDTO)
        {
            using (var db=new RentHouseEntities())
            {
                var bs = new BaseService<T_AdminUsers>(db);
                //判断手机号
                var model = bs.Get(p => p.PhoneNum == loginDTO.PhoneNum);
                if (model == null)
                {
                    return new AjaxResult(ResultState.Error, "手机号不存在");
                }
                else
                {
                    //判断密码
                    string pwd = CommonHelper.CalcMD5(loginDTO.Password + model.PasswordSalt);
                    if (model.PasswordHash != pwd)
                    {
                        return new AjaxResult(ResultState.Error, "密码不正确");
                    }
                    else
                    {
                        //如果密码一致，则进行登录
                        LoginAdminDTO loginAdminDTO = new LoginAdminDTO()
                        {
                            Id = model.Id,
                            Name = model.Name,
                            PhoneNum = model.PhoneNum,
                            RoleName = model.T_Roles.Count > 0 ? model.T_Roles.FirstOrDefault().Name : "",
                            CityId = model.CityId == null ? 0 : model.CityId.Value
                        };
                        //调用SaverData方法，在客户端保存Cookie信息，以保存用户登录状态
                        SaverData(loginAdminDTO, loginDTO.IsRemeberMe);
                        return new AjaxResult(ResultState.Success, "登录成功");
                    }
                }
            }
        }
        /// <summary>
        /// 缓存用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="isRemeberMe"></param>
        public void SaverData(LoginAdminDTO user, bool isRemeberMe)
        {
            //1、序列化要保存的用户信息
            var data = user.ToJson();

            //2、创建一个FormsAuthenticationTicket，它包含登录名以及额外的用户数据。
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, user.Name, DateTime.Now, DateTime.Now.AddDays(1), true, data);

            //3、加密保存
            string cookieValue = FormsAuthentication.Encrypt(ticket);

            // 4. 根据加密结果创建登录Cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
            cookie.HttpOnly = true;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            //若用户勾选记得我，则指定cookie有效期（ Expires ）
            if (isRemeberMe)
            {
                cookie.Expires = DateTime.Now.AddDays(1);
            }

            // 5. 写登录Cookie（获取http请求上下文HttpContext ，移除原来的数据，存入新的）
            HttpContext.Current.Response.Cookies.Remove(cookie.Name);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}
